import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic
import paho.mqtt.client as mqtt

import hmac
from hashlib import sha1
import paho.mqtt.client as mqtt
import json
import time

from DAO import dao


# from UI import do_question_window
# from mysql import mysql

# class do_question(do_question_window, mysql):
class cloud_ui(QMainWindow, dao):
    def __init__(self):
        super().__init__()
        self.init_cloud_ui()

    def init_cloud_ui(self):
        self.ui = uic.loadUi("./Cloud_app.ui")
        self.init_mqtt_login_message()
        self.init_cloud_login_ui()
        self.init_cloud_status_ui()
        self.init_cloud_control_led_ui()
        self.init_windows_switch()

    def init_windows_switch(self):
        # self.C_actionCloud = self.ui.C_actionCloud
        self.C_actionLocate = self.ui.C_actionlocate
        self.C_actionLocate.triggered.connect(self.local_window)
        self.C_actionLocate.triggered.connect(self.ui.close)

    def init_mqtt_login_message(self):
        self.port = 1883
        # self.mqttClientId = "a1HlgPIyR1D.Intelligent_thermomterV2_1_up|securemode=2,signmethod=hmacsha256,timestamp=1689333526556|"
        # self.mqttUsername = 'Intelligent_thermomterV2_1_up&a1HlgPIyR1D'
        # self.mqttPassword = 'c98429817d9450a89ec9f6421052fdec3523ce9273b859a08bd81327a3911f1c'
        # self.mqttHostUrl  = 'a1HlgPIyR1D.iot-as-mqtt.cn-shanghai.aliyuncs.com'
        #
        # self.subTopic = "/sys/a1HlgPIyR1D/Intelligent_thermomterV2_1_up/thing/service/property/set"
        # self.pubTopic = "/sys/a1HlgPIyR1D/Intelligent_thermomterV2_1_up/thing/event/property/post"
        self.mqttClientId = "a1HlgPIyR1D.Intelligent_thermomterV2_song_up|securemode=2,signmethod=hmacsha256,timestamp=1689357051061|"
        self.mqttUsername = 'Intelligent_thermomterV2_song_up&a1HlgPIyR1D'
        self.mqttPassword = '82058013011bf4b9584fa5597cad0ec78999322215ab1cb9323f764612dad182'
        self.mqttHostUrl  = 'a1HlgPIyR1D.iot-as-mqtt.cn-shanghai.aliyuncs.com'

        self.subTopic = "/sys/a1HlgPIyR1D/Intelligent_thermomterV2_song_up/thing/service/property/set"
        self.pubTopic = "/sys/a1HlgPIyR1D/Intelligent_thermomterV2_song_up/thing/event/property/post"
    def init_cloud_login_ui(self):
        self.C_login_user    = self.ui.C_loginUser
        self.C_login_passwd  = self.ui.C_loginPasswd
        self.C_login_url     = self.ui.C_loginUrl
        self.C_login_port    = self.ui.C_loginPort
        self.C_loginClientId = self.ui.C_loginClientId
        self.C_login_button  = self.ui.C_connectButton
        self.C_exit_button   = self.ui.C_exitButton

        self.C_login_button.clicked.connect(self.cloud_login)
        self.C_exit_button.clicked.connect(self.cloud_exit)

        self.C_login_user.setText(self.mqttUsername)
        self.C_login_passwd.setText(self.mqttPassword)
        self.C_login_url.setText(self.mqttHostUrl)
        self.C_loginClientId.setText(self.mqttClientId)
        self.C_login_port.setText(str(self.port))
        self.C_login_button.setEnabled(True)
        self.C_exit_button.setEnabled(False)

    def connect_mqtt(self):
        def on_connect(client, userdata, flags, rc):
            if rc == 0:
                print("连接成功\n")
                self.C_status_cloud.setText('是')
                self.C_button_led_on.setEnabled(True)
                self.C_button_led_off.setEnabled(True)
            else:
                print("连接失败\n")
        client = mqtt.Client(self.C_loginClientId.text())
        client.username_pw_set(username=self.C_login_user.text(), password=self.C_login_passwd.text())
        client.on_connect = on_connect
        client.connect(self.C_login_url.text(), int(self.C_login_port.text()))
        return client

    def on_message(self, client, userdata, msg):
        try:
            topic = msg.topic
            # payload = msg.payload.decode()
            payload = msg.payload.decode()
            print("topic:" + topic)
            print("payload：" + payload)

            CurrentHumidity = eval(msg.payload)['items']['CurrentHumidity']['value']
            CurrentTemperature = eval(msg.payload)['items']['CurrentTemperature']['value']
            LEDSwitch = eval(msg.payload)['items']['LEDSwitch']['value']

            self.C_status_temperature.setText(str(CurrentTemperature))
            self.C_status_humidity.setText(str(CurrentHumidity))
            self.C_status_led.setText(str(LEDSwitch))
            print("\n")

            if ("thing/service/property/set" in topic):
                self.on_thing_prop_changed(client, msg.topic, msg.payload)
        except Exception:
            pass

    def on_thing_prop_changed(self, client, topic, payload):
        post_topic = topic.replace("service", "event")
        post_topic = post_topic.replace("set", "post")
        Msg = json.loads(payload)
        params = Msg['params']
        post_payload = "{\"params\":" + json.dumps(params) + "}"
        print("收到属性设置的指令，需要主动上报属性变化的topic：" + post_topic)
        print("收到属性设置的指令，需要主动上报属性变化的payload：" + post_payload)
        print("    ")
        client.publish(post_topic, post_payload)

    def cloud_login(self):
        self.client = self.connect_mqtt()
        self.client.loop_start()
        self.client.on_message = self.on_message
        self.client.subscribe(self.subTopic)

        self.C_login_button.setEnabled(False)
        self.C_exit_button.setEnabled(True)

    def cloud_exit(self):
        self.client.disconnect()
        self.client.loop_stop()
        self.C_status_cloud.setText('否')
        print('连接断开')
        self.C_login_button.setEnabled(True)
        self.C_exit_button.setEnabled(False)

        self.C_button_led_on.setEnabled(False)
        self.C_button_led_off.setEnabled(False)

    def init_cloud_status_ui(self):
        self.C_status_temperature = self.ui.C_Temperature
        self.C_status_humidity    = self.ui.C_Humidity
        self.C_status_cloud       = self.ui.C_cloudStatus
        self.C_status_led         = self.ui.C_ledStatus
        self.C_led                = self.ui.C_led

        self.C_status_temperature.setText('')
        self.C_status_humidity.setText('')
        self.C_status_led.setText('')
        self.C_status_cloud.setText('否')

        self.C_led.setText('')

    def init_cloud_control_led_ui(self):
        self.C_button_led_on  = self.ui.C_ledOnButton
        self.C_button_led_off = self.ui.C_ledOffButton

        self.C_button_led_on.clicked.connect(self.button_led_on)
        self.C_button_led_off.clicked.connect(self.button_led_off)

        self.C_button_led_on.setEnabled(False)
        self.C_button_led_off.setEnabled(False)

    def button_led_on(self):
        palyload = '{"params": {"LEDSwitch": {"value": 1}}}'
        self.client.publish(self.pubTopic, palyload)
        print(palyload)


    def button_led_off(self):
        palyload = '{"params": {"LEDSwitch": {"value": 0}}}'
        self.client.publish(self.pubTopic, palyload)
        print(palyload)

    def local_window(self):
        from LOCAL_UI import local_ui
        self.w1 = local_ui()
        # self.w1.ui.setWindowIcon(QIcon("./yss.ico"))
        self.w1.setWindowTitle("本地串口控制")
        self.w1.ui.show()


    # def cloud_window(self):
    #     self.w2 = cloud_ui()
    #     # self.w2.ui.setWindowIcon(QIcon("./yss.ico"))
    #     self.w2.setWindowTitle("云端远程控制")
    #     self.w2.ui.show()



if __name__ == "__main__":
    app = QApplication(sys.argv)
    a = cloud_ui()
    a.ui.setWindowTitle("云平台控制")
    a.ui.show()
    app.exec()
